package com.jt.ktdemo.ui.changePwd

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.Window
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.jt.ktdemo.R
import com.jt.ktdemo.bean.BackBean
import com.jt.ktdemo.bean.PersonCallbackBean
import com.jt.ktdemo.databinding.PasswordBinding
import com.jt.ktdemo.http.HTTPAPI
import com.jt.ktdemo.listener.EditTextInputListener
import com.jt.ktdemo.utils.GsonUtils
import com.jt.ktdemo.utils.LogUtil
import com.jt.ktdemo.utils.SpUtils
import com.jt.ktdemo.view.VerificationCodeView
import com.lzy.okgo.callback.StringCallback
import kotlinx.android.synthetic.main.password.*
import okhttp3.Call
import okhttp3.Response
import java.lang.Exception

class ChangePwdActivity : AppCompatActivity(), View.OnClickListener {

    private lateinit var binding: PasswordBinding
    private lateinit var btModule: TextView
    private lateinit var etModuleEmail: EditText

    private lateinit var etModulePwd: EditText
    private lateinit var etModulePwdAgain: EditText
    private lateinit var vcModule: VerificationCodeView

    private var type: Int = 0
    private var TYPE_FIRST: Int = 0
    private var TYPE_SECOND: Int = 1
    private var TYPE_THIRD: Int = 2

    private var firstEditText : Boolean = false
    private var secondEditText : Boolean = false
    private var thirdEditText : Boolean = false
    private var forthEditText : Boolean = false

    var pwdPoint: Boolean = true
    var pwdAgainPoint: Boolean = true
    val sampleDrawables = intArrayOf(R.drawable.yanjing_xianshi_o, R.drawable.yanjing_yincang_o)

    //验证码输入框监听
    private lateinit var editTextInputListener : EditTextInputListener

    private var handler : Handler = object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            LogUtil.e("接收handler 信息")

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        binding = DataBindingUtil.setContentView(this, R.layout.password)
        binding.activity = this
        initView()
    }

    private fun initView() {
        binding.btModule.text = "Continue"
        /**
         * 第一关： 输入邮箱
         */
        etModuleEmail = findViewById(R.id.etModuleEmail)
        etModuleEmail.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                /**
                 * 第一关相关，输入康收集邮箱号
                 */
                firstEditText = !TextUtils.isEmpty(s.toString())
                checkFirstEditBoolean(firstEditText)
            }
        })

        etModulePwd = findViewById(R.id.etModulePwd)
        etModulePwdAgain = findViewById(R.id.etModulePwdAgain)
        vcModule = findViewById(R.id.vcModule)
        btModule = findViewById(R.id.btModule)
        btModule.setOnClickListener(this)



        /**
         * 第三关，改密码
         */
        binding.etModulePwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                /**
                 * 第三关相关，输入康收集邮箱号
                 */
                thirdEditText = !TextUtils.isEmpty(s.toString())
                checkFirstEditBoolean(thirdEditText&&forthEditText)
            }
        })

        /**
         *
         */
        binding.etModulePwdAgain.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                /**
                 * 第三关相关，输入康收集邮箱号
                 */
                forthEditText = !TextUtils.isEmpty(s.toString())
                checkFirstEditBoolean(thirdEditText&&forthEditText)
            }
        })

        //启用验证码输入框输入监听
        binding.vcModule.setOnEditTextInputListener(object : EditTextInputListener{
            override fun setOnEditTExtInputListener(b: Boolean) {
                if (b) {
                    checkFirstEditBoolean(true)
                    secondEditText = true
                }else{
                    checkFirstEditBoolean(false)
                    secondEditText = true
                }
            }
        })

        /**
         * 输入验证码眼睛点击事件
         */
        binding.ivModulePwd.setOnClickListener {
            if (pwdPoint) {
                pwdPoint = false
                binding.ivModulePwd.setImageResource(sampleDrawables[0])
                etModulePwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                pwdPoint = true
                binding.ivModulePwd.setImageResource(sampleDrawables[1])
                etModulePwd.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
            binding.etModulePwd.setSelection(etModulePwd.text.toString().length)
        }

        /**
         * 再次输入验证码眼睛点击事件
         */
        binding.ivModulePwdAgain.setOnClickListener {
            if (pwdAgainPoint) {
                pwdAgainPoint = false
                binding.ivModulePwdAgain.setImageResource(sampleDrawables[0])
                etModulePwdAgain.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                pwdAgainPoint = true
                binding.ivModulePwdAgain.setImageResource(sampleDrawables[1])
                etModulePwdAgain.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
            etModulePwdAgain.setSelection(etModulePwdAgain.text.toString().length)
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btModule ->
                when {
                    TYPE_FIRST === type -> {
                        /**
                         * 按钮没有点击事件，不响应
                         */
                        if (!firstEditText) {
                            return;
                        }

                        var email = binding.etModuleEmail.text.toString().trim()
                        if (email.isEmpty()) {
                            Toast.makeText(this, "input your Email !", Toast.LENGTH_SHORT).show()
                            return
                        }
                        var name = SpUtils["module_name", ""].toString()
                        sendCode(name, email)
                    }
                    TYPE_SECOND === type -> {

                        if (!secondEditText) {
                            return
                        }

                        if (binding.vcModule.isFinish) {
                            LogUtil.e("验证码输入完毕")
                            var code = binding.vcModule.content
                            LogUtil.e("验证码-->"+ code)
                            if (!code.isEmpty()) {
                                LogUtil.e("验证码非空，联网检测验证码")
                                checkCode(code)
                            }
                        } else {
                            Toast.makeText(this, "input your code !", Toast.LENGTH_SHORT).show()
                        }
                    }
                    TYPE_THIRD === type -> {

                        if (!thirdEditText || !forthEditText) {
                            return;
                        }

                        var pwd = binding.etModulePwd.text.toString().trim()
                        if (pwd.isEmpty()) {
                            Toast.makeText(this, "input your password !", Toast.LENGTH_SHORT).show()
                            return
                        }
                        var pwdAgain = binding.etModulePwdAgain.text.toString().trim()
                        if (pwdAgain.isEmpty()) {
                            Toast.makeText(this, "input your password again!", Toast.LENGTH_SHORT)
                                .show()
                            return
                        }
                        updatePwd(pwd, pwdAgain)

                    }
                }
        }
    }


    /**
     * 向邮箱发送验证码
     */
    private fun sendCode(name: String, email: String) {
        HTTPAPI.sendCode(name, email, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("验证码发送成功-->$t")

                var bean: BackBean = GsonUtils.parse(t.toString(), BackBean::class.java)

                if (!TextUtils.isEmpty(bean.getSession())) {
                    SpUtils.put("module_session", bean.getSession())
                }

                type = TYPE_SECOND
                etModuleEmail.visibility = View.GONE
                vcModule.visibility = View.VISIBLE
                /**
                 * 1 标题改写
                 * 2 提示内容改写
                 * 3 显示验证码输入框
                 * 4 重置按钮点击事件
                 */
                binding.textView8.text = "Verification Code"
                binding.textView10.text = "Enter 4 digits code than you"
                binding.textView11.text = "recevied on your email"
                binding.btModule.text = "Continue"

                handler.sendEmptyMessage(0)

                checkFirstEditBoolean(false)
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("验证码发送失败-->${e!!.message}")
            }
        })
    }

    private fun checkCode(mailCode: String) {
        HTTPAPI.checkCode(mailCode, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("验证码验证成功-->$t")
                type = TYPE_THIRD
                etModuleEmail.visibility = View.GONE
                vcModule.visibility = View.GONE

                binding.rlModulePwd.visibility = View.VISIBLE
                binding.rlModulePwdAgain.visibility = View.VISIBLE
                binding.vModulePwd.visibility = View.VISIBLE
                binding.vModulePwdAgain.visibility = View.VISIBLE

                binding.textView8.text = "Reset Password"
                binding.textView10.text = "Set new password for your"
                binding.textView11.text = "next login &amp; access in ISOMA"
                binding.btModule.text = "Reset Now"
                /**
                 * 第三关：初始化按钮
                 */
                checkFirstEditBoolean(false)
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("验证码验证失败-->${e!!.message}")
            }
        })
    }

    /**
     * 更新密码
     */
    private fun updatePwd(pwd: String, pwdAgain: String) {
        HTTPAPI.updatePwd(pwd, pwdAgain, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                LogUtil.e("密码更新成功-->$t")

                type = TYPE_FIRST

                binding.rlModulePwd.visibility = View.GONE
                binding.rlModulePwdAgain.visibility = View.GONE
                binding.vModulePwd.visibility = View.GONE
                binding.vModulePwdAgain.visibility = View.GONE


                etModuleEmail.visibility = View.VISIBLE
                Toast.makeText(
                    this@ChangePwdActivity,
                    "Password changed successfully !",
                    Toast.LENGTH_SHORT
                ).show()
                finish()
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                LogUtil.e("密码更新失败-->${e!!.message}")
            }
        })
    }

    @SuppressLint("NewApi")
    fun checkFirstEditBoolean(b : Boolean) {
        if (b) {
            binding.btModule.setBackgroundResource(R.drawable.draw_module_login_bg)
        } else {
            binding.btModule.setBackgroundResource(R.drawable.draw_module_login_bg_selected)
        }
    }
}